from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.infrastructure.db.models import AllowedIP, Order, User


async def get_ip(session: AsyncSession, ip_id: int) -> AllowedIP:
    q = select(AllowedIP).where(AllowedIP.id == ip_id)

    res = await session.execute(q)

    return res.scalar()


async def add_ip_to_order(session: AsyncSession, order: Order, allowed_ip: AllowedIP) -> None:
    order.allowed_ips.append(allowed_ip)

    await session.commit()


async def remove_ip_from_order(session: AsyncSession, order: Order, allowed_ip: AllowedIP) -> None:
    order.allowed_ips.remove(allowed_ip)

    await session.commit()


async def get_allowed_ips(session: AsyncSession, user_id: int) -> list[AllowedIP]:
    q = select(AllowedIP).outerjoin(AllowedIP.user).filter(User.telegram_id == user_id)

    res = await session.execute(q)

    return res.scalars().all()


async def get_allowed_ip_by_order(session: AsyncSession, user_id: int, order_id: int) -> AllowedIP:
    q = (
        select(AllowedIP)
        .join(AllowedIP.orders)
        .join(AllowedIP.user)
        .filter(Order.id == order_id)
        .filter(User.telegram_id == user_id)
    )

    res = await session.execute(q)

    return res.scalar()
